<template>
  <div>
    <search-bar ref="searchRef" :data="searchSchema" @search="onSearch" @add="addItem" />
    <dynamic-table
      ref="tableRef"
      :columns="columns"
      :get-list-func="getAdminAccount"
      rowKey="id"
    >
      <template v-slot:status="{ record }">
        <a-switch
          v-model:checked="record.status"
          @change="onChangeStatus(record)"
        />
      </template>
    </dynamic-table>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  createVNode,
  computed,
  ref
} from 'vue'
import { Modal } from 'ant-design-vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import { DynamicTable } from '@/components/dynamic-table'
import { SearchBar } from '@/components/search-bar'
import { getAdminAccount, updateStatus, addAccount } from '@/api/system/ums'
import { columns, getFormSchema, getSearchSchema } from './schema'
import { useFormModal } from '@/hooks/useFormModal'
import md5 from 'blueimp-md5'

export default defineComponent({
  name: 'ums-admin',
  components: {
    DynamicTable,
    SearchBar
  },
  setup() {
    const tableRef = ref<any>(null)
    const searchRef = ref<any>(null)

    const state = reactive({
      tableLoading: false,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          state.rowSelection.selectedRowKeys = selectedRowKeys
        },
        selectedRowKeys: []
      }
    })

    // 启用禁用
    const onChangeStatus = row => {
      Modal.confirm({
        title: '提示',
        icon: createVNode(QuestionCircleOutlined),
        content: '是否要修改该状态？',
        onOk: async () => {
          await updateStatus(row.id, { status: row.status ? 1 : 0 })
          tableRef.value.refreshTableData()
        },
        onCancel: async () => {
          tableRef.value.refreshTableData()
        }
      })
    }

    // 添加账号
    const addItem = () => {
      useFormModal({
        title: '添加账号',
        formSchema: getFormSchema(),
        handleOk: async (modelRef, state) => {
          const params = { ...modelRef, password: md5(modelRef.password) }
          await addAccount(params)
          tableRef.value.refreshTableData()
        }
      })
    }

    const isDisabled = computed(
      () => state.rowSelection.selectedRowKeys.length == 0
    )

    const onSearch = params => {
      tableRef.value.refreshTableData(params)
    }

    const searchSchema = getSearchSchema()

    return {
      ...toRefs(state),
      columns,
      tableRef,
      searchRef,
      getAdminAccount,
      isDisabled,
      onChangeStatus,
      addItem,
      searchSchema,
      onSearch
      // deleteItems,
    }
  }
})
</script>
